'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 1. 创建role的ENUM类型
    await queryInterface.sequelize.query(`
      CREATE TYPE "enum_users_role" AS ENUM ('user', 'moderator', 'admin', 'superadmin');
    `).catch(error => {
      // 如果ENUM类型已存在，忽略错误
      console.log('ENUM类型可能已存在，继续执行下一步');
    });

    // 2. 添加role字段
    await queryInterface.addColumn('users', 'role', {
      type: Sequelize.ENUM('user', 'moderator', 'admin', 'superadmin'),
      allowNull: false,
      defaultValue: 'user'
    });
    
    // 3. 添加permissions字段
    await queryInterface.addColumn('users', 'permissions', {
      type: Sequelize.JSON,
      allowNull: true
    });
    
    // 4. 添加created_by和updated_by字段
    await queryInterface.addColumn('users', 'created_by', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id'
      }
    });
    
    await queryInterface.addColumn('users', 'updated_by', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id'
      }
    });
    
    // 5. 将admin用户设为管理员
    await queryInterface.sequelize.query(
      `UPDATE users SET role = 'admin' WHERE username = 'admin'`
    );
  },

  down: async (queryInterface, Sequelize) => {
    // 1. 删除字段
    await queryInterface.removeColumn('users', 'role');
    await queryInterface.removeColumn('users', 'permissions');
    await queryInterface.removeColumn('users', 'created_by');
    await queryInterface.removeColumn('users', 'updated_by');
    
    // 2. 删除ENUM类型
    await queryInterface.sequelize.query(`
      DROP TYPE IF EXISTS "enum_users_role";
    `);
  }
}; 